import type { Plugin } from 'vite'
import { readFileSync, writeFileSync } from 'fs'
import { resolve } from 'path'

export interface ModulePreloadOptions {
  /**
   * 是否启用modulepreload
   */
  enabled?: boolean
}

export function viteModulePreloadPlugin(options: ModulePreloadOptions = {}): Plugin {
  const { enabled = true } = options
  
  if (!enabled) {
    return {
      name: 'vite-plugin-modulepreload-disabled'
    }
  }

  return {
    name: 'vite-plugin-modulepreload',
    apply: 'build',
    // 确保在SRI插件之前运行
    enforce: 'pre',
    writeBundle(options, bundle) {
      const htmlFilePath = resolve(options.dir || 'dist', 'index.html')
      
      try {
        let htmlContent = readFileSync(htmlFilePath, 'utf-8')
        
        // 收集所有的chunk文件（懒加载的JS文件）
        const chunkFiles: string[] = []
        
        for (const [fileName, chunk] of Object.entries(bundle)) {
          if (chunk.type === 'chunk' && !chunk.isEntry && fileName.endsWith('.js')) {
            chunkFiles.push(fileName)
          }
        }
        
        if (chunkFiles.length === 0) {
          return
        }
        
        // 生成modulepreload链接（不包含integrity，让SRI插件后续添加）
        const modulePreloadLinks = chunkFiles
          .map(fileName => `    <link rel="modulepreload" as="script" crossorigin href="/${fileName}">`)
          .join('\n')
        
        // 在</head>标签前插入modulepreload链接
        htmlContent = htmlContent.replace(
          '</head>',
          `${modulePreloadLinks}\n  </head>`
        )
        
        writeFileSync(htmlFilePath, htmlContent, 'utf-8')
        
        console.log(`🔗 Added ${chunkFiles.length} modulepreload links to index.html`)
        chunkFiles.forEach(file => {
          console.log(`   - /assets/${file}`)
        })
        
      } catch (error) {
        console.error('Error adding modulepreload links:', error)
      }
    }
  }
}